// index.js
const app = getApp()
var that
Page({
  data: {
    list: [],
    q: '',
    cart: [],
    money: 0,
    popTop: 0,
    num: '',
    sn: '',
    phone:'',
    hasPhoneNumber:false
  },
  onLoad(query) {
    var scanCode = query.scanCode;
    console.log("query-==",scanCode)
    var baseSn;
    if(scanCode != null && scanCode !=''){
       baseSn = scanCode;
    }else{
      const q = decodeURIComponent(query.q) // 获取到二维码原始链接内容
      console.log("q==",q)
      let _i1 = q.split('?')[1]
      let _i2 = _i1.split('=')[1]
      baseSn = _i2;
    }
    app.globalData.baseSn = baseSn;
    this.setData({
      sn:baseSn
    })
    // app.globalData.baseSn = '865074057782194'
    that = this
  },
  onShow(){
    this.login()
    this.setPop()
  },

  login() {
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log('Login code:', res.code);
          this.requestHttp('/app/auth/wechat/login', { code: res.code }, 'get').then(({ data }) => {
              const app = getApp();
              app.globalData.token = 'Bearer ' + data.token;
              app.globalData.type = data.type;
              console.log(app.globalData.token)
              this.getUser();
          });
        }
      }
    });
  },

  getUser(){
    this.requestHttp('/app/customer/info', '', 'get').then((data) => {
      console.log(data.data.phone)
      if (data.data.phone !== ""){
        this.setData({
          phone:data.data.phone,
          hasPhoneNumber:true
        })
      }
      console.log(this.data.hasPhoneNumber)
      this.getList()
    })
  },
  getList(){
    // app.globalData.baseSn = '865074057782194';
    console.log("app.globalData.baseSn",app.globalData.baseSn)
    this.requestHttp('/app/client/deviceGoods/' + app.globalData.baseSn, '', 'get').then(({data}) => {
      var list = []
      for(var i = 0; i < data.length; i++){
        list.push({
          ...data[i],
          num: 0
        })
      }
      that.setData({
        list
      })
    })
  },

  setItemData(id, type){
    var item = this.data.list
    for(var i = 0; i < item.length; i++){
      if(item[i].id * 1 === id * 1){
        if(!type){
          var obj = {
            ...item[i],
            num: type ? (item[i].num + 1) : (item[i].num - 1)
          }
          this.setCartList(obj, i)
        } else if(item[i].goodsStock > item[i].num){
          var obj = {
            ...item[i],
            num: type ? (item[i].num + 1) : (item[i].num - 1)
          }
          this.setCartList(obj, i)
        }
        return
      }
    }
  },
  setCartList(obj, i){
    var list = this.data.list
    list.splice(i, 1, obj)
    var money = 0
    var num = 0
    var cart = list.filter((item) => {
      console.log(item)
      if(item.num && item.num > 0) {
        money = item.num * item.goodsPrice + money 
        num = item.num + num
        return true
      } else {
        return false
      }
    })
    this.setData({
      list,
      cart,
      money,
      num
    })
  },
  reduce(e){
    var id = e.currentTarget.dataset.id
    this.setItemData(id)
  },
  addData(e){
    var id = e.currentTarget.dataset.id
    this.setItemData(id, '+')
  },
  toPay(){
    if(this.data.cart && this.data.cart.length > 0){
      var obj = {
        "deviceId": 12, //设备ID
        "payChannel": "wechat", //支付渠道
        "details": [] //商品详情
      }
      for(var i = 0; i < this.data.cart.length; i++){
        obj.deviceId = this.data.cart[i].deviceId
        obj.details.push({
          "cargoId": this.data.cart[i].id, //货道id
          "num": this.data.cart[i].num //购买数量
        })
      }
      this.requestHttp('/app/order/create', obj, 'post').then(({data}) => {
        console.log(data)
        wx.requestPayment({
          ...data,
          success(r) {
            console.log(r);
            console.log("购买成功")
            //清空购物车、刷新列表
            that.setData({
              list: [],
              cart: [],
              money: 0,
              num: '',
            })
            that.getUser()
          },
          fail(r) {
            console.log(r);
          },
        });
      })
    } else {
      wx.showToast({
        title: '请选择商品！',
        icon: 'none',
      })
    }
  },
  setPop(){
    var h = wx.getSystemInfoSync().windowHeight
    console.log(that.data.popTop)
    this.setData({
      popTop: that.data.popTop ? 0 : h
    })
  },
  bannerBtn(){
    wx.showToast({
      title: '敬请期待！',
      icon: 'none',
    })
  },
  // 处理获取手机号的回调函数
  getPhoneNumber(e) {
    console.log(e.detail.code)
    // 检查用户是否同意授权
    if (e.detail.code) {
      const code = e.detail.code;

      // 发送请求到后端解密手机号
      this.requestHttp('/app/customer/getPhone', {code: code}, 'get').then(({data}) => {

        console.log(data)
        this.toPay()
        //更新手机号信息
        var obj = {
          "phone": data, //用户手机号
        }
        console.log(obj)
        this.requestHttp('/app/customer/edit', obj, 'post').then(({data}) => {
          console.log(data)
        })

      });
    } else {
      console.log('用户拒绝授权');
      this.toPay()
    }
  },
  requestHttp(url,data,method){
    return new Promise(function (reslove, reject) {
      console.log(app.globalData.token)
      let headers = {
        'Authorization': app.globalData.token || ''
      };
      wx.request({
        url: app.globalData.host + url,
        method: method || 'get',
        data: data,
        header: headers,
        success: function success(res) {
          const data = res.data;
          if (data.code * 1 === 0) {
            reslove(data)
          } else {
            wx.showToast({
              title: data.msg || '网络异常',
              icon: 'error',
            })
            setTimeout(() => {
              reject(data);
            }, 10)
          }
          // reslove(res)
        },
        fail: function fail(res) {
          wx.showToast({
            title: res,
            icon: 'error',
          })
          reject(res);
        }
      })
    })
  }
})
